
import * as mUtils from '@/utils/mUtils'
import { doLoginOut ,getUserInfo } from '@/api/user'  // 导入用户信息相关接口
import { getToken, setToken, removeToken } from '@/utils/auth'
import constant from "@/utils/constant";


const user  = {
  state : {
    name:'',
    avatar:'',
    token: getToken('Token'),
    roles: [],
    browserHeaderTitle: mUtils.getStore('browserHeaderTitle') || '小爱Admin'
  },
  getters : {
    token: state => state.token,
    roles: state => state.roles,
    avatar: state => state.avatar,
    name: state => state.name,
    browserHeaderTitle: state => state.browserHeaderTitle,
  },
  mutations: {
    SET_ROLES: (state, roles) => {
        state.roles = roles
    },
    SET_BROWSERHEADERTITLE: (state, action) => {
        state.browserHeaderTitle = action.browserHeaderTitle
    },
    SET_NAME: (state, name) => {
      state.name = name
    },
    SET_AVATAR: (state, avatar) => {
      state.avatar = avatar
    }
  },
  actions:{
    //登出
    LogOut({commit, reqData}) {
      return new Promise((resolve, reject) => {
//      commit('SET_TOKEN', '');
        commit('SET_ROLES', []);
//      commit("SET_USER_ID", '');
//      commit("SET_USER_NAME", '');
        commit("SET_AVATAR", '');
        removeToken(getToken(constant.TOKEN));
        removeToken(constant.TOKEN);
        sessionStorage.removeItem(sessionStorage.getItem('token'));
        sessionStorage.removeItem('token');
        sessionStorage.removeItem('userInfo');
        sessionStorage.removeItem('loginForm');
		//清除所有
		sessionStorage.clear();
        resolve();
      });
    },
      // 动态修改权限;本实例中,role和token是相同的;
      ChangeRoles({ commit }, role) {
        return new Promise(resolve => {
          const token = role;
          setToken("Token",token)
          getUserInfo({"token":token}).then(res => {
            let data = res.data.userList;
            commit('SET_ROLES', data.roles)
            commit('SET_NAME', data.name)
            commit('SET_AVATAR', data.avatar)
            resolve()
          })
        })
      },
    // 缓存用户信息;
    saveUserLogin({commit}, data) {
      return new Promise(resolve => {
        const token = data.token;
        setToken(constant.TOKEN, token);
//      setToken(token, JSON.stringify(data),1/48);
        sessionStorage.setItem(constant.TOKEN,token)
        sessionStorage.setItem(token,JSON.stringify(data))
        sessionStorage.setItem('userInfo',JSON.stringify(data.userKeyInfo))
      	localStorage.setItem(token,JSON.stringify(data));
      	localStorage.setItem('newUndr_randomStr',data.newUndr_randomStr);
        resolve();
      })
    },
      
  }
}

export default user;

/**
 * 1、用户退出,需要调取后台接口吗？后台具体的业务逻辑是什么？
 * 
 * 
 */